
//
//  shouwenViewController.m
//  OASystem
//
//  Created by michael on 16/11/4.
//  Copyright © 2016年 zpf. All rights reserved.
//

#import "UIViewExt.h"
#import "NSArray+Log.h"
#import "SelectAlert.h"

#import "shouwenViewController.h"
#import "OADetailDisPatchController.h"
#import "OADetailDisPatchCell.h"
#import "HttpTools.h"
#import "GDataDefines.h"
#import "OADetailDispatchModel.h"
#import "OAToolBox.h"
#import "OAAttachmentsModel.h"
#import "MBProgressHUD.h"
#import "OAAttachmentsModel.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "Toast+UIView.h"
#import "UIAlertView+Blocks.h"
#import "OASelectPersonSecondController.h"

@interface shouwenViewController ()<QLPreviewControllerDataSource,QLPreviewControllerDelegate,TFPickerDelegate,UITextViewDelegate,UIWebViewDelegate>
{
    NSInteger selectIndex;
        NSArray *titles;

}
@property(nonatomic,strong)OADetailDispatchModel * detailPatchModel;
@property(nonatomic,strong)NSMutableArray * attachmentArray;
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件



@property (strong, nonatomic)NSArray *array;
@property (strong, nonatomic) MHDatePicker *selectDatePicker;
@property (strong, nonatomic)  UITextView *danweiField;
@property (strong, nonatomic)  UITextView *wenhaoField;
@property (strong, nonatomic)  UITextView *biaotiField;
@property (strong, nonatomic)  UITextView *shuomingField;
@property (strong, nonatomic)  UITextView *bianhaoField;
@property (strong, nonatomic)  UITextView *nianduField;






@end

@implementation shouwenViewController
-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}
-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _web = [[UIWebView alloc]initWithFrame:self.view.frame];
    _web.delegate = self;
//    _web.backgroundColor = [UIColor clearColor];
    _web.hidden = YES;
    [self.view addSubview:_web];

 self.tableView.hidden = NO;
    self.title = @"收文登记";
      NSDate *currentDate = [NSDate date];//获取当前时间，日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY"];
_datestring = [dateFormatter stringFromDate:currentDate];
//_datestring = _date;

//    self.view.backgroundColor = [UIColor clearColor];
//              self.automaticallyAdjustsScrollViewInsets = NO;
self.edgesForExtendedLayout = UIRectEdgeNone;

//_tableView.backgroundColor = [UIColor yellowColor];
    [self loadData];
}
- (void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:kexchgregbookurl arrays:array method:@"saveRegbook" success:^(id JSON) {
    NSLog(@"-------%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailPatchModel = [self getDetailModel:JSON];
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
//获取解析得到的数据。
-(OADetailDispatchModel *)getDetailModel:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempArray) {
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
            
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
            
            GDataXMLElement *shouwen= [[data elementsForName:@"GwOrigUnit"] objectAtIndex:0];
            NSString *string = [shouwen stringValue];
            _array = [string componentsSeparatedByString:@","];
            
             GDataXMLElement *riqi= [[data elementsForName:@"GwNum"] objectAtIndex:0];
            detailModel.riqi = [riqi stringValue];
            
             GDataXMLElement *laiwen= [[data elementsForName:@"GwIssueDate"] objectAtIndex:0];
            detailModel.laiwendanwei = [laiwen stringValue];
            
                GDataXMLElement *hangwen= [[data elementsForName:@"GwSwClass"] objectAtIndex:0];
            detailModel.hangwen = [hangwen stringValue];
            
              GDataXMLElement *biaoti= [[data elementsForName:@"swfs"] objectAtIndex:0];
            detailModel.biaoti = [biaoti stringValue];

            
            
            
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
    
//    NSArray * tempArray0 = [subData elementsForName:@"数据对照"];
//            for (GDataXMLElement * element in tempArray0) {

        NSArray * tempArray = [subData elementsForName:@"正文实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 9;
            break;
       case 1:
            return self.mainattachmentArray.count;
        case 2:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
    
      if (indexPath.row==0) {

 static NSString *cellid0 = @"cell0";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid0];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 80, cell.contentView.height)];
    label.text = @"收文分类 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
 _shouwenbutton = [UIButton buttonWithType:UIButtonTypeCustom];
        _shouwenbutton.layer.borderColor = [[UIColor blackColor] CGColor];
      _shouwenbutton.frame = CGRectMake(label.right, label.top, KScreenWidth-100, label.height);
//    _button1.backgroundColor = [UIColor yellowColor];
      [_shouwenbutton setTitle:@"选择类型" forState:UIControlStateNormal];
    _shouwenbutton.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    _shouwenbutton.titleLabel.textAlignment = NSTextAlignmentLeft;
                 [_shouwenbutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
           [_shouwenbutton addTarget:self action:@selector(placeaction) forControlEvents:UIControlEventTouchUpInside];

 
       [cell.contentView addSubview:_shouwenbutton];
       }
             return cell;
    }
    else if(indexPath.row == 1){
 static NSString *cellid1 = @"cell1";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid1];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 80, cell.contentView.height)];
    label.text = @"收文日期 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
     _databutton = [UIButton buttonWithType:UIButtonTypeCustom];
      _databutton.frame = CGRectMake(label.right, label.top, 100, label.height);
      
      
          _databutton.titleLabel.font = [UIFont systemFontOfSize: 13.0];
     [_databutton setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
     [_databutton addTarget:self action:@selector(dataaction) forControlEvents:UIControlEventTouchUpInside];
     _databutton.layer.borderColor = [[UIColor blackColor] CGColor];
       [cell.contentView addSubview:_databutton];
      
    

        }
            [_databutton setTitle: _detailPatchModel.riqi forState:UIControlStateNormal];

             return cell;



}

    else if(indexPath.row ==2){
static NSString *cellid2 = @"cell2";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid2];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid2];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"来文单位 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _danweiField = [[UITextView alloc]init];
           _danweiField.layer.borderColor = [[UIColor blackColor] CGColor];
      _danweiField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _danweiField.backgroundColor = myColor;
 [_danweiField setFont:[UIFont systemFontOfSize:12]];
      _danweiField.delegate = self;
       [cell.contentView addSubview:_danweiField];
       }
       _danweiField.text = _detailPatchModel.laiwendanwei;
             return cell;
}
     else if(indexPath.row ==3){
static NSString *cellid3 = @"cell3";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid3];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid3];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"行文问号 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _wenhaoField = [[UITextView alloc]init];
           _wenhaoField.layer.borderColor = [[UIColor blackColor] CGColor];
      _wenhaoField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _wenhaoField.backgroundColor = myColor;
 [_wenhaoField setFont:[UIFont systemFontOfSize:12]];
      _wenhaoField.delegate = self;
       [cell.contentView addSubview:_wenhaoField];
       }
       _wenhaoField.text = _detailPatchModel.hangwen;
             return cell;
}
 else if(indexPath.row ==4){
static NSString *cellid4 = @"cell4";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid4];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid4];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"标题 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _biaotiField = [[UITextView alloc]init];
           _biaotiField.layer.borderColor = [[UIColor blackColor] CGColor];
      _biaotiField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _biaotiField.backgroundColor = myColor;
 [_biaotiField setFont:[UIFont systemFontOfSize:12]];
      _biaotiField.delegate = self;
       [cell.contentView addSubview:_biaotiField];
       }
              _biaotiField.text = _detailPatchModel.biaoti;

             return cell;
}
else if(indexPath.row ==5){
static NSString *cellid5 = @"cell5";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid5];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid5];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"附加说明 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _shuomingField = [[UITextView alloc]init];
           _shuomingField.layer.borderColor = [[UIColor blackColor] CGColor];
      _shuomingField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, 100-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _shuomingField.backgroundColor = myColor;
 [_shuomingField setFont:[UIFont systemFontOfSize:12]];
      _shuomingField.delegate = self;
       [cell.contentView addSubview:_shuomingField];
       }
             return cell;
}
else if(indexPath.row ==6){
static NSString *cellid6 = @"cell6";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid6];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid6];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"文件编号 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _bianhaoField = [[UITextView alloc]init];
           _bianhaoField.layer.borderColor = [[UIColor blackColor] CGColor];
      _bianhaoField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _bianhaoField.backgroundColor = myColor;
 [_bianhaoField setFont:[UIFont systemFontOfSize:12]];
      _bianhaoField.delegate = self;
       [cell.contentView addSubview:_bianhaoField];
       }
                     _bianhaoField.text = _info;

             return cell;
}
    else if(indexPath.row ==7){
static NSString *cellid7 = @"cell7";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid7];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid7];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
   UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"收文年度 :";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
      _nianduField = [[UITextView alloc]init];
           _nianduField.layer.borderColor = [[UIColor blackColor] CGColor];
      _nianduField.frame = CGRectMake(label.right, label.top+10, KScreenWidth-120, cell.height-10);
      UIColor *myColor = [UIColor colorWithWhite:0.5 alpha:0.2];
      _nianduField.backgroundColor = myColor;
 [_nianduField setFont:[UIFont systemFontOfSize:12]];
      _nianduField.delegate = self;
       [cell.contentView addSubview:_nianduField];
       }
       _nianduField.text = _datestring;
             return cell;
}
else{
 
static NSString *cellid8 = @"cell8";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellid8];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid8];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 100, cell.contentView.height)];
    label.text = @"内部公开 :";
     label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
    
      _selectview2 = [selectupboxView checkBoxFootView];
      _selectview2.frame = CGRectMake(label.right, label.top, KScreenWidth-110, label.height);
       [cell.contentView addSubview:_selectview2];}
          return cell;
 }

    }else if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;
            
        }else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;

        }

    
    
}

//类型选择
- (void)placeaction{
PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.view.bounds];
    picker.delegate = self;
           picker.selectLb.text = @"类型选择";
        picker.customArr = _array;
    [self.view addSubview:picker];
    
}
- (void)PickerSelectorIndixString:(NSString *)str{


[_shouwenbutton setTitle:str forState:UIControlStateNormal];
_shouwen = str;
// 进行网络请求
[self updata];
}
- (void)updata{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId},@{@"type":_shouwen}];
    [HttpTools postWithURL:kexchgregbookurl arrays:array method:@"getRegNumber" success:^(id JSON) {
    NSLog(@"-------%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
         GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    GDataXMLElement *rootElement = [doc rootElement];
    NSArray *infoArray= [rootElement elementsForName:@"info"];
    for (int i = 0;i<[infoArray count];i++)
    {
        GDataXMLElement *infoElement = [infoArray objectAtIndex:i];
        self.info = [infoElement stringValue];
    }

        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
//日期选择
- (void)dataaction{
 _selectDatePicker = [[MHDatePicker alloc] init];
    _selectDatePicker.isBeforeTime = YES;
    _selectDatePicker.datePickerMode = UIDatePickerModeDate;
    
    __weak typeof(self) weakSelf = self;
    [_selectDatePicker didFinishSelectedDate:^(NSDate *selectedDate) {
      NSString *string = [weakSelf dateStringWithDate:selectedDate DateFormat:@"yyyy-MM-dd"];
      _detailPatchModel.riqi = string;
      [weakSelf.databutton setTitle: _detailPatchModel.riqi forState:UIControlStateNormal];
    }];

}
- (NSString *)dateStringWithDate:(NSDate *)date DateFormat:(NSString *)dateFormat
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    NSString *str = [dateFormatter stringFromDate:date];
    return str ? str : @"";
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
    if (_mainattachmentArray.count !=0) {
     return 21;

}else{

 return 0.001;


}
    
    
           }
    if (section==2) {
 if (_attachmentArray.count!=0) {
     return 21;

}else{

 return 0.001;


}
    }
    return 0.001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat height = 54;
    if (indexPath.section == 0) {
        if(indexPath.row ==5)   {
        
        return 100;
        }else{
            return height;
        
        }
    }else if(indexPath.section == 1||indexPath.section == 2){
                return height;
    }
    return height;
}
- (void)textViewDidChange:(UITextView *)textView
{
if(textView ==_danweiField){
_detailPatchModel.laiwendanwei = _danweiField.text;
}
if(textView ==_wenhaoField){
_detailPatchModel.hangwen = _wenhaoField.text;
}
if(textView ==_biaotiField){
_detailPatchModel.biaoti = _biaotiField.text;
}
if(textView ==_nianduField){
_datestring= _nianduField.text;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"正文";
//        label.backgroundColor = [UIColor yellowColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.mainattachmentArray.count!= 0) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
        if (section==2) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
//        label.backgroundColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        [bgView addSubview:label];
        if (self.attachmentArray.count!= 0) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        return bgView;
    }
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
        
        
        [self openFileURL:model.attachmentsURL];
    }else if (indexPath.section == 2){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        NSLog(@"%@",model.attachmentsURL);

        
        [self openFileURL:model.attachmentsURL];
    }
    
}

-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
 
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
     [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
      return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}


//输入框被键盘遮住
- (void)textViewDidBeginEditing:(UITextView *)textView{
    CGRect frame = textView.frame;
    int offset = frame.origin.y + 32 - (self.tableView.frame.size.height - 216.0-80);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    if(textView ==_shuomingField||textView ==_bianhaoField||textView ==_nianduField){
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    self.tableView.frame = CGRectMake(0.0f, offset, self.tableView.frame.size.width, self.tableView.frame.size.height);
    
    [UIView commitAnimations];
    }   
}


- (void)textViewDidEndEditing:(UITextView *)textView{
    self.tableView.frame =CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height);
}




- (IBAction)save:(id)sender {
if(!_shouwen){
        [self.view makeToast:@"对不起，收文分类为空"];
}
//else if([_shuomingField.text length] ==0){
//        [self.view makeToast:@"对不起，附加说明为空"];
//}
//else if([_bianhaoField.text length] ==0){
//        [self.view makeToast:@"对不起，文件编号为空"];
//}
else{
_type = @"保存";
if ([_selectview2.orderString isEqualToString:@"0"]) {
    _neibu = @"本单位公开";
} else {
    _neibu = @"只公开给选择的人员";
}
    [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];



self.body = [NSString stringWithFormat:@"&lt;?xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n"
                     "&lt;交换 xmlns=\'exch.jhsx.gov.cn/data\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\'&gt;\n"
                     "&lt;数据&gt;\n"
                     "&lt;数据要素&gt;\n"
                     "&lt;唯一标识&gt;\n"
                     "%@"
                     "&lt;/唯一标识&gt;\n"
                     "&lt;GwOrigUnit  name='收文分类'&gt;\n"
                     "%@"
                     "&lt;/GwOrigUnit&gt;\n"
                     "&lt;GwNum  name='收文日期'&gt;\n"
                     "%@"
                     "&lt;/GwNum&gt;\n"
                     "&lt;GwIssueDate  name='来文单位'&gt;\n"
                     "%@"
                     "&lt;/GwIssueDate&gt;\n"
                     "&lt;GwSwClass  name='行文文号'&gt;\n"
                     "%@"
                     "&lt;/GwSwClass&gt;\n"
                     "&lt;swfs  name='标  题'&gt;\n"
                     "%@"
                     "&lt;/swfs&gt;\n"
                     "&lt;swfs  name='附加说明'&gt;\n"
                     "%@"
                     "&lt;/swfs&gt;\n"
                     "&lt;GwHurry  name='文件编号'&gt;\n"
                     "%@"
                     "&lt;/GwHurry&gt;\n"
                     "&lt;sendtype  name='收文年度'&gt;\n"
                     "%@"
                     "&lt;/sendtype&gt;\n"
                     "&lt;GwFileClass  name='内部公开'&gt;\n"
                     "%@"
                     "&lt;/GwFileClass&gt;\n"
                     "&lt;/数据要素&gt;\n"
                      "&lt;数据对照&gt;\n"
                       "&lt;正文实体&gt;\n"
                       "&lt;/正文实体&gt;\n"
                       "&lt;/数据对照&gt;\n"
                       "&lt;数据实体&gt;\n"
                        "&lt;附件&gt;\n"
                     "%@"
                     "&lt;/附件&gt;\n"
                       "&lt;/数据实体&gt;\n"
                     "&lt;/数据&gt;\n"
                     "&lt;/交换&gt;",
                     self.detailPatchModel.fileId,
                     self.shouwen,
                     self.detailPatchModel.riqi,
                     self.detailPatchModel.laiwendanwei,
                     self.detailPatchModel.hangwen,
                     self.detailPatchModel.biaoti,
                     self.shuomingField.text,
                     self.bianhaoField.text,
                     self.datestring,
                     self.neibu,
                     [self returnString]];
  NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array =@[@{@"sName":userId},@{@"formxml":self.body}];
    NSLog(@"%@",_body);
[HttpTools postWithURL:kexchgregbookurl arrays:array method:@"regbookSave"  success:^(id JSON) {
    _infoString0 = [NSString stringWithFormat:@"%@",JSON];
    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
//     NSData * data = [JSON dataUsingEncoding:NSUTF8StringEncoding];
//     GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
//    GDataXMLElement *rootElement = [doc rootElement];
//      
//          NSArray *infoData= [rootElement elementsForName:@"info"];
//    for (int i = 0;i<[infoData count];i++)
//    {
//        GDataXMLElement *infoElement = [infoData objectAtIndex:i];
//        self.infoString0 = [infoElement stringValue];
//    }
    if ([self.infoString0 isEqualToString:@"20"]) { //成功发送，提交下一办理人
        
        [self.view.window makeToast:@"保存成功!"];
       
    }
          
    else if ([self.infoString0 isEqualToString:@"1044"]){
    
    [self.view.window makeToast:@"服务器出错"];

    }else{
    
    [self.view.window makeToast:@"保存失败,请再试一次!"];
    }
   } failure:^(NSError *error) {
    [self.view.window makeToast:@"保存失败,请再试一次!"];
    }];
    }
}


-(NSString *)returnString

{
    NSString *string = [[NSString alloc]init];
    string = @"&lt;名称&gt;%@&lt;/名称&gt;\n"
    "&lt;内容&gt;%@&lt;/内容&gt;\n";
    
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i<self.attachmentArray.count; i++) {
        OAAttachmentsModel * attachModel = self.attachmentArray[i];
        [str appendString: [NSString stringWithFormat:string,attachModel.attachmentsTitle,attachModel.attachmentsURL]];
    }
    
    return str;
}
- (IBAction)qiyong:(id)sender {
if (![_type isEqualToString:@"保存"]) {
[self.view makeToast:@"请先保存!"];
        }else{
//            titles = @[@"设置性别为男",@"设置性别为女"];
//
//        [SelectAlert showWithTitle:@"设置性别" titles:titles selectIndex:^(NSInteger selectIndex) {
//        
//        
//    
//    } selectValue:^(NSString *selectValue) {
//    NSLog(@"%@",selectValue);
//    for (NSString *string in titles) {
//    if ([selectValue isEqualToString:string]) {
//NSLog(@"%@",string);
//}
//}
 UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
         OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[storyBoard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
    detailVC.fileId = _detailPatchModel.fileId;
    detailVC.isAlreadDoneWork = YES;
                detailVC.isUnDoWork = NO;
detailVC.type = @"dengji";
    [self.navigationController pushViewController:detailVC animated:YES];


//} showCloseButton:YES];
        
        
        
        
//        UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//         OADetailDisPatchController * detailVC = (OADetailDisPatchController*)[storyBoard instantiateViewControllerWithIdentifier:@"OADetailDispatchVC"];
//    detailVC.fileId = _detailPatchModel.fileId;
//    detailVC.isAlreadDoneWork = YES;
//                detailVC.isUnDoWork = NO;
//detailVC.type = @"dengji";
//    [self.navigationController pushViewController:detailVC animated:YES];
        }
}
@end
